import time
from PIL import Image
import io
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import ddddocr

ocr = ddddocr.DdddOcr(show_ad=False)

DEBUG = True

service = Service(executable_path="D:\\chromedriver.exe")

driver = webdriver.Chrome(service=service)

driver.get("http://127.0.0.1:8000/captcha_show/")

while True:

	captcha = driver.find_element(By.CLASS_NAME, 'captcha')


	# captcha_bytes = captcha.screenshot_as_png
	# code = ocr.classification(captcha_bytes)
	# print(code)
	# if DEBUG:
	# 	with open(f"./codes/django_code_{code}.jpg", "wb") as f:
	# 		f.write(captcha_bytes)


	captcha_b64 = captcha.screenshot_as_base64
	code = ocr.classification(captcha_b64)
	print(code)




	# 保存整个屏幕截图
	# driver.save_screenshot("./codes/screen.png")


	# captcha.rect
	# captcha.location
	# captcha.size

	# 自定义区域截图
	# screen_bytes = driver.get_screenshot_as_png()
	# img = Image.open(io.BytesIO(screen_bytes))
	#
	# img_cropped  = img.crop([captcha.location['x'], captcha.location['y'], captcha.location['x']+captcha.size['width'], captcha.location['y']+ captcha.size['height']])
	# img_cropped.save("./codes/img_cropped.png")




	id_captcha_1 = driver.find_element(By.ID, 'id_captcha_1')
	id_captcha_1.send_keys(f"{code}")


	time.sleep(1)

	submit = driver.find_element(By.XPATH, '//input[@type="submit"]')
	submit.click()

	try:
		driver.find_element(By.ID, "success")
		print(driver.get_cookies(), "cookies")
		break
	except Exception as e:
		print(f"识别失败， 重试")
		time.sleep(1)



input()
driver.quit()


